import {Component, OnInit, ViewEncapsulation, ViewChild, Input, OnDestroy} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {ModalComponent} from "@shared/components/modal/modal.component";
import {CrowdService} from "@crowd/crowd.service";
import {Subscription} from "rxjs/Subscription";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";
// import {
//   CrowdDetailResp, CrowdSkuResVO, CrowdSupporterResp,
//   CrowdDynamicRespVO
// } from "@interface/crowd.model";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {Subject} from "rxjs";
import {ImageServeService} from "@shared/service/image/image-serve.service.ts";
import {CrowdDetailResp, CrowdDynamicRespVO, CrowdSkuResVO, CrowdSupporterResp} from "@interface/index";



@Component({
  selector: 'seed-crowd-details',
  templateUrl: './crowd-details.component.html',
  styleUrls: ['./crowd-details.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CrowdDetailsComponent implements OnInit, OnDestroy {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild(ModalComponent) modal;
  @Input() crowdSku: CrowdSkuResVO[];

  @Input()
  set url(url: string) {
    this._StateUrl = this.imgService.getCrowdStateImg(url);
  }

  get url() {
    return this._StateUrl;
  }

  public _StateUrl: string;
  public crowdLaunch = false;
  public crowdCode: string;
  public content: any;
  public params: any = {
    'crowdCode': '',
    'page': 1,
    'rows': 10
  };
  public pageCache = {
    page1: 1, //  支持者
    page2: 1, //  活动动态
  };
  //  将加载过的数据存储在数组中，再次打开不重复加载，
  public loadState = {
    loadEndArr: []
  };
  /*
   * 0,草稿,1,待审核(crowd_pending) 2,审核未通过(crowd_not_pass) 3,众筹中(crowding)，
   * 4，众筹成功(crowd_completed) 5，众筹失败(crowd_defeated),6已下架(crowd_colded_out) 7已禁用 ,
   * */
  public statusPicture = ['draft', 'pending', 'notPass', 'crowding', 'completed', 'defeated', 'coldOut'];
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public soldOvered = false;
  public soldOuted = true;
  public crowdStauts = true;
  public crowdSuccess = false;
  public goodsCode: string;
  public getSku = true;
  public crowdDetail: CrowdDetailResp;
  public supporterList: Array<CrowdSupporterResp> = [];  // 支持者列表
  public dynamicList: Array<CrowdDynamicRespVO> = [];  // 活动动态列表
  public supporterTotal = 0; // 支持者列表总数
  public dynamicTotal = 0; // 活动动态列表总数
  public hasLogin = false;
  public index: number;
  public crowdStatu: number;
  public userId: string;
  public city: string;
  public skuShow = true;
  public editSkuShow = true;

  constructor(public router: Router,
              public crowdService: CrowdService,
              private route: ActivatedRoute,
              public toolBarService: ToolbarService,
              public toolsService: ToolsService,
              private auth: AuthService,
              private imgService: ImageServeService) {
    if (this.auth.hasLoggedIn()) {
      this.hasLogin = true;
    }
    this.route.queryParams.subscribe(param => {
      this.crowdCode = param['crowdCode'];
      this.getCrowdDetail(param['crowdCode']);
    });

  }

  ngOnInit() {

  }

  /**
   * @description 获取众筹详情
   * @author baoww765 部分@其他人
   * @date 2017-11-15
   * @param crowdCode
   */
  getCrowdDetail(crowdCode: string) {
    this.userId = this.auth.getUserId();
    //  console.log(this.userId);
    this.toolsService.hideLoading();
    this.crowdService.getCrowdDetail(crowdCode, this.userId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          this.crowdDetail = res.data;
          this.goodsCode = res.data.goodsCode;
          this.params.crowdCode = res.data.crowdCode;
          this.getCrowdSupporters(this.params);
          this.getCrowdDynamics(this.params);
          this.crowdStatu = res.data.crowdStatus;
          this.toolsService.hideLoading();
          this.url = this.statusPicture[this.crowdStatu];
          if (this.crowdDetail.userBaseResp.userId === this.userId) {
            this.crowdLaunch = true;
          }
          if (this.crowdSuccess === true) {
            this.url = this.statusPicture[4];
          }
        }
      });
  }

  /**
   * @description 获取支持者列表
   * @author @zhupw1360
   * @date 2017-11-16
   * @param params { crowdCode , page , rows }
   */
  getCrowdSupporters(params) {
    params.page = this.pageCache.page1;
    this.crowdService.getCrowdSupporters(params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.pageCache.page1++;
        this.infiniteScroll.complete();
        if (!res.data.hasNextPage) {
          this.loadState.loadEndArr.push(1);
          this.infiniteScroll.enable(false);
        }
        this.supporterList = [...this.supporterList, ...res.data.list];
        this.supporterTotal = res.data.total ? res.data.total : 0;
      }
    });
  }

  /**
   * @description 获取活动动态列表
   * @author @zhupw1360
   * @date 2017-11-16
   * @param params { crowdCode , page , rows }
   */
  getCrowdDynamics(params) {
    params.page = this.pageCache.page2;
    this.crowdService.getCrowdDynamics(params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.pageCache.page2++;
        this.infiniteScroll.complete();
        if (!res.data.hasNextPage) {
          this.loadState.loadEndArr.push(2);
          this.infiniteScroll.enable(false);
        }
        this.dynamicList = [...this.dynamicList, ...res.data.list];
        this.dynamicTotal = res.data.total ? res.data.total : 0;
      }
    });
  }

  /**
   * @description 在不同tab，判断下是否需下拉刷新，加载更多 (滚动时执行当前页面内容下拉刷新，加载)
   * @author @zhupw1360
   * @date 2017-11-17
   * @param index
   */
  handleScrollLoading() {
    if (this.loadState.loadEndArr.indexOf(this.index) !== -1) {
      return this.infiniteScroll.enable(false);
    }
    if (this.index === 1 && this.pageCache.page1 > 1) {
      this.getCrowdSupporters(this.params);
    } else if (this.index === 2 && this.pageCache.page2 > 1) {
      this.getCrowdDynamics(this.params);
    }
  }

  /**
   * @description 点击获取tab的index，判断当前选中tab页面是否可以执行滚动，)
   * @author @zhupw1360
   * @date 2017-11-17
   * @param tab.index ,  tab的下标
   */
  getTabIndex(tab) {
    const index = tab.index;
    this.index = index;
    if (index === 0) {
      this.infiniteScroll.enable(false);
    } else {
      if (this.loadState.loadEndArr.indexOf(tab.index) !== -1) { // 加载完的tab
        if (this.infiniteScroll) {
          this.infiniteScroll.enable(false);
        }
        // this.infiniteScroll && this.infiniteScroll.enable(false);
      } else {  // 未加载完的tab
        if (this.infiniteScroll) {
          this.infiniteScroll.enable(true);
        }
        // this.infiniteScroll && this.infiniteScroll.enable(true);
      }
    }
  }

  /**
   *@description 获取sku信息
   * @author baoww765
   * @date 2017-11-18
   * @param crowdCode goodsCode
   **/
  getSkuInfo(crowdCode, goodsCode) {
    this.crowdService.getSkuInfo(crowdCode, goodsCode)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.crowdSku = res.data;
        this.getSku = false;
      }
    });
  }

  /**
   * @description 详情页按钮
   * @author @zhoukf1349
   * @date 2017-11-16
   * @param index
   */

  // 百分比轉化
  matchPersent(str: string) {
    const a = str.replace(/%/, "");
    if (parseInt(a, 10) < 100) {
      return true;
    } else if (parseInt(a, 10) >= 100) {
      return false;
    }
  }

  /**
   * @description 支持Ta 点击支持他,判断是否登录，
   * @author:  baoww765
   * */
  buySku() {
    if (this.auth.hasLoggedIn()) {
      this.hasLogin = true;
      if (!this.crowdSku && this.getSku) {
        this.getSkuInfo(this.crowdCode, this.goodsCode);
      }
      // !this.crowdSku && this.getSku && this.getSkuInfo(this.crowdCode, this.goodsCode);
      this.modal.show();
      this.skuShow = !this.skuShow;
    } else {
      this.toolsService.presentConfirm('此操作需要登录,是否前往登录', 1, this.goToLogin.bind(this));
      return;
    }
  }

  goToLogin() {
    this.router.navigate(['/auth/login']);
  }

  /*权益列表中按钮弹出模态框，关闭按钮*/
  /**
   * @description 关闭sku页面
   * @author baoww765
   * @date 2017-11-15
   * */
  closeSku() {
    this.modal.hide();
    this.modal.goBack();
    this.skuShow = !this.skuShow;
    this.editSkuShow = !this.editSkuShow;
  }

  /**
   * @description 重新编辑众筹，编辑之前判断用户当日是否还可以发起众筹，判断用户是否认证
   * @author:  baoww765
   * @date 2017-11-15
   */
  editToDeal() {
    this.crowdService.getCanAdd().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.router.navigate([`/crowd/protocol`], {queryParams: {crowdCode: this.params.crowdCode}});
      } else if (res.result === '50001') {
        this.toolsService.showToast('已达今日发起上限，请明日再来发起');
      } else if (res.result === '2110') {
        this.toolsService.showToast('想要发布众筹？请到求苗APP进行用户认证');
      } else {
        this.toolsService.showToast(res.msg);
      }
    });
  }

  /*管理活动状态*/
  manageToStatus() {
    this.router.navigate([`/crowd/dynamic-manage`], {queryParams: {crowdCode: this.params.crowdCode}});
  }

  /*权益列表*/
  entitleTable() {
    if (!this.crowdSku && this.getSku) {
      this.getSkuInfo(this.crowdCode, this.goodsCode);
    }
    // !this.crowdSku && this.getSku && this.getSkuInfo(this.crowdCode, this.goodsCode);
    this.editSkuShow = !this.editSkuShow;
    this.modal.show();
  }

  /*提前结束*/
  headEnd() {
    this.toolsService.presentConfirm('确定提前结束众筹？', 1, '', this.headEeded.bind(this), '是', '否');
  }

  headEeded() {
    const data = {
      crowdCode: this.crowdCode
    };
    this.crowdService.completeCrowd(data).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.url = this.statusPicture[4];
        this.crowdDetail.crowdStatus = 4;
        this.toolsService.showToast('已成功结束众筹！您的众筹成功！', 2000);
      };
    });
  }

  /**
   * @description 再次发起,判断用户当日是否还可以发起众筹，判断用户是否IP认证
   * @author baoww765
   * @date 2017-11-15
   * */
  launchAgain() {
    this.crowdService.getCanAdd().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.router.navigate([`/crowd/protocol`], {queryParams: {crowdCode: this.params.crowdCode}});
      } else if (res.result === '50001') {
        this.toolsService.showToast('已达今日发起上限，请明日再来发起');
      } else if (res.result === '2110') {
        this.toolsService.showToast('想要发布众筹？请到求苗APP进行用户认证');
      } else {
        this.toolsService.showToast(res.msg);
      }
    });
  }

  /*上架*/
  pushCrowd() {
    this.toolsService.presentConfirm('确定上架？', 1, '', this.submitInfo.bind(this), '是', '否');
  }

  /**
   * @description 上架，判断众筹活动截止时间是否早于当前时间
   * @author baoww765
   * @date 2017-11-15
   * */
  submitInfo() {
    const data = {
      crowdCode: this.crowdCode
    };
    const nowTime = new Date().getTime();

    this.crowdService.getCanAdd().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        if (parseInt(this.crowdDetail.crowdEndTime, 10) > nowTime) {
          this.crowdService.onRackCrowd(data).takeUntil(this.ngUnsubscribe).subscribe(datas => {
            if (datas.result === '0') {
              this.router.navigate([`/crowd/launch-result`], {queryParams: {crowdCode: datas.data.crowdCode}});
            }
          });
        } else {
          this.toolsService.showToast('请您重新编辑之后再发布众筹');
        }
      } else if (res.result === '50001') {
        this.toolsService.showToast('已达今日发起上限，请明日再来发起');
      } else if (res.result === '2110') {
        this.toolsService.showToast('想要发布众筹？请到求苗APP进行用户认证');
      } else {
        this.toolsService.showToast(res.msg);
      }
    });
  }

  /*下架*/
  soldOut() {
    this.toolsService.presentConfirm('确定下架?其筹得的资金将退给用户！', 1, '', this.soldOver.bind(this), '是', '否');
  }

  soldOver() {
    const data = {
      crowdCode: this.crowdCode
    };
    this.crowdService.offRackCrowd(data).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.soldOvered = true;
        this.soldOuted = false;

      }
    });
    this.url = this.statusPicture[6];
    this.crowdDetail.crowdStatus = 6;
  }

  /*删除*/
  deleteInfo() {
    this.toolsService.presentConfirm('确定删除？', 1, '', this.deleteCrowd.bind(this), '是', '否');
  }

  deleteCrowd() {
    this.crowdService.delOutCrowd(this.crowdCode).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.toolsService.showToast('您已删除该众筹！', 2000);
        this.router.navigate([`/crowd/my-crowd`]);
      }
    });
  }

  goToHomepage(userId) {
    this.router.navigate(['/', userId]);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
